using Microsoft.AspNetCore.Mvc; // 引入ASP.NET Core MVC命名空间，提供控制器相关功能
using 后端服务.Models; // 引入模型命名空间，包含VideoDto和PagedResult类
using 后端服务.Services; // 引入服务命名空间，包含IVideoService接口

namespace 后端服务.Controllers;

/// <summary>
/// 视频控制器，处理视频相关的API请求
/// </summary>
[ApiController] // 标记为API控制器，启用API特定行为
[Route("api/[controller]")] // 定义API路由前缀为"api/Videos"
public class VideosController : ControllerBase // 继承自ControllerBase，提供控制器基本功能
{
    private readonly IVideoService _videoService; // 视频服务，处理业务逻辑
    private readonly ILogger<VideosController> _logger; // 日志记录器，用于记录控制器操作日志

    /// <summary>
    /// 构造函数，通过依赖注入初始化控制器
    /// </summary>
    /// <param name="videoService">视频服务实例</param>
    /// <param name="logger">日志记录器实例</param>
    public VideosController(IVideoService videoService, ILogger<VideosController> logger)
    {
        _videoService = videoService; // 初始化视频服务
        _logger = logger; // 初始化日志记录器
    }

    /// <summary>
    /// 搜索视频API端点
    /// </summary>
    /// <param name="query">搜索关键词</param>
    /// <param name="page">当前页码，默认为1</param>
    /// <param name="pageSize">每页记录数，默认为10</param>
    /// <returns>分页的视频列表结果</returns>
    [HttpGet("search")] // 定义HTTP GET请求路由为"api/Videos/search"
    public async Task<ActionResult<PagedResult<VideoDto>>> Search(
        [FromQuery] string query, // 从查询字符串获取搜索关键词
        [FromQuery] int page = 1, // 从查询字符串获取页码，默认为1
        [FromQuery] int pageSize = 10) // 从查询字符串获取每页大小，默认为10
    {
        try
        {
            // 调用服务层方法执行搜索
            var result = await _videoService.SearchVideosAsync(query, page, pageSize);
            
            // 返回200 OK状态码和分页结果
            return Ok(result);
        }
        catch (Exception ex)
        {
            // 记录异常日志
            _logger.LogError(ex, "Error occurred while searching videos");
            // 返回500 Internal Server Error状态码和错误消息
            return StatusCode(500, "An error occurred while searching videos");
        }
    }

    /// <summary>
    /// 获取单个视频详情API端点
    /// </summary>
    /// <param name="id">视频ID</param>
    /// <returns>视频详情</returns>
    [HttpGet("{id}")] // 定义HTTP GET请求路由为"api/Videos/{id}"
    public async Task<ActionResult<VideoDto>> GetVideo(long id)
    {
        try
        {
            // 调用服务层方法获取视频详情
            var video = await _videoService.GetVideoByIdAsync(id);
            
            // 如果未找到视频，返回404 Not Found状态码
            if (video == null)
            {
                return NotFound($"Video with ID {id} not found");
            }

            // 返回200 OK状态码和视频详情
            return Ok(video);
        }
        catch (Exception ex)
        {
            // 记录异常日志
            _logger.LogError(ex, "Error occurred while retrieving video with ID {VideoId}", id);
            // 返回500 Internal Server Error状态码和错误消息
            return StatusCode(500, "An error occurred while retrieving the video");
        }
    }

    /// <summary>
    /// 下载视频文件API端点
    /// </summary>
    /// <param name="id">视频ID</param>
    /// <returns>视频文件流</returns>
    [HttpGet("{id}/download")] // 定义HTTP GET请求路由为"api/Videos/{id}/download"
    public async Task<IActionResult> DownloadVideo(long id)
    {
        try
        {
            // 调用服务层方法获取视频文件信息
            var fileInfo = await _videoService.GetVideoFileInfoAsync(id);
            if (fileInfo == null)
            {
                return NotFound($"Video file with ID {id} not found");
            }

            var (filePath, fileName, mimeType) = fileInfo.Value;

            // 检查文件是否存在
            if (string.IsNullOrEmpty(filePath) || !System.IO.File.Exists(filePath))
            {
                return NotFound($"Video file with ID {id} not found on server");
            }

            // 使用PhysicalFile返回文件流，指定MIME类型和文件名
            return PhysicalFile(filePath, mimeType, fileName);
        }
        catch (Exception ex)
        {
            // 记录异常日志
            _logger.LogError(ex, "Error occurred while downloading video with ID {VideoId}", id);
            // 返回500 Internal Server Error状态码和错误消息
            return StatusCode(500, "An error occurred while downloading the video");
        }
    }
}